import React, {Component} from 'react'
import { Map, is } from 'immutable';
import {
    Button,
    Input,
    InputNumber,
    Select,
    Form,
    Row,
    Col,
    Radio,
    DatePicker,
    message
} from 'antd';
import { fetchData } from '../../../components/AjaxConsumer'
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
import moment from 'moment';
const dateFormat = 'YYYY-MM-DD HH:mm:ss'; //DatePicker格式
const formItemLayout = {
    labelCol: {
        span: 6
    },
    wrapperCol: {
        span: 14
    },
};
const buttonItemLayout  = {
    wrapperCol: {
        span: 24,
        offset: 9,
    },
};

export default class OtherInfoForm extends React.Component {
    constructor(props) {
        super(props);
        this.typeSelect = [];
        this.state = {
            isAdd: true, //办单默认是新增一条数据
            objectInfo: {},
            selectOptionList: []
        };
    }

    //提交事件
    saveHandle = (values) => {
        let saveData = {...values};
        console.log('修改保存========', saveData);
        const options= {
            url: '/base/custother/u',
            type: 'post',
            condition:{
                ...saveData
            }
        };
        fetchData(this, options, (resData) => {
            if(resData.code == "1"){
                this.resetHandle();//修改成功后重置表单
                this.props.refreshHandle();//修改成功后刷新list列表
            }else{
                console.log("请求数据错误：", resData.message);
            }
        });
    }

    addHandle = (values) => {
        let searchCondition = this.props.searchCondition;//查询条件，创建新数据拼装上查询条件
        let addData = {...values, ...searchCondition}

        if(searchCondition.custCode != "" && searchCondition.custCode != undefined){
            console.log("addData====", addData)
            //TODO 添加事件
            const options= {
                url: '/base/custother/c',
                type: 'post',
                condition:{
                    ...addData
                }
            };
            fetchData(this, options, (resData) => {
                if(resData.code == "1"){
                    this.resetHandle();//添加成功后重置表单
                    this.props.refreshHandle();//添加成功后刷新list列表
                }else{
                    console.log("请求数据错误：", resData.message);
                }
            });
        }else{
            message.warn("请先选择客户或新建一个客户！");
        }
    }

    componentDidMount(){
        const options= {
            url: '/base/dic/get/cust_type',
            type: 'get'
        };
        fetchData(this, options, (resData) => {
            if(resData.code == "1"){
                this.setState({
                    selectOptionList : resData.data
                });//添加成功后重置表单
                
            }else{
                console.log("请求数据错误：", resData.message);
            }
        });
    }

    deleteHandle = () => {

        //TODO 执行删除事件

    }

    resetHandle = () => {
        this.props.form.resetFields();
    }
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, fieldsValue) => {
            if (!err) {
                const values = {//有时间类型的需要再次处理
                    ...fieldsValue,
                    'expirationDate': fieldsValue['expirationDate'].format('YYYY-MM-DD HH:mm:ss'),
                    'effectiveDate': fieldsValue['effectiveDate'].format('YYYY-MM-DD HH:mm:ss')
                }

                console.log('form表单值=====', values);
                if(this.state.isAdd){//新增添加
                    this.addHandle(values);
                }else{//修改保存
                    this.saveHandle(values);
                }
            }
        });
    }

    componentWillReceiveProps(nextProps) {
        let blCompare = false;  //比较搜索条件是否变化，如果没有变化不执行查询
        const map1 = Map(this.props.rowObject);
        const map2 = Map(nextProps.rowObject);
        if(!is(map1, map2)){
            blCompare = true;
        }
        if(blCompare){
            this.props.form.resetFields();
            this.setState({
                isAdd: nextProps.isAdd,
                objectInfo:  nextProps.rowObject
            });
        }
    }

    render() {
        const { getFieldDecorator, setFieldsValue } = this.props.form;
        let objectInfo = this.state.objectInfo;
        let optionData = this.state.selectOptionList ? this.state.selectOptionList : [];
        const colNumber = 8;//一行3个
        let actionButtons;
        if(this.state.isAdd){//新增
            actionButtons = (

                <Row className="infoForm_row">
                    <FormItem {...buttonItemLayout}>
                        <Col span={2} >
                            <Button type='primary' htmlType="submit" >新增</Button>
                        </Col>
                        <Col span={2} >
                            <Button type='default' onClick={this.resetHandle}>重置</Button>
                        </Col>
                    </FormItem>
                </Row>
            )
        }else{//修改、删除
            actionButtons = (
                <Row className="infoForm_row">
                    <FormItem {...buttonItemLayout}>
                        <Col span={2} >
                            <Button type='primary' htmlType="submit">保存</Button>
                        </Col>
                        <Col span={2} >
                            <Button type='danger' onClick={this.deleteHandle}>删除</Button>
                        </Col>
                        <Col span={2} >
                            <Button type='default' onClick={this.resetHandle}>重置</Button>
                        </Col>
                    </FormItem>
                </Row>
            )
        }
        return (
            <div className="infoForm">
                <Form onSubmit={this.handleSubmit}>
                    <FormItem  style={{display: 'none'}}>
                        {
                            getFieldDecorator('custOtherId', {
                                rules: [{ required: false}],
                                initialValue: objectInfo.custOtherId? objectInfo.custOtherId : ""
                            })(
                                <Input placeholder="请输入" />
                            )}
                    </FormItem>
                    <FormItem  style={{display: 'none'}}>
                        {
                            getFieldDecorator('custCode', {
                                rules: [{ required: false}],
                                initialValue: objectInfo.custCode? objectInfo.custCode : ""
                            })(
                                <Input placeholder="请输入" />
                            )}
                    </FormItem>
                    <Row className="infoForm_row">

                        <Col span={colNumber} >
                            <FormItem  {...formItemLayout} label="类型">
                                {
                                    getFieldDecorator('custType', {
                                        rules: [{ required: true, message: '请选择类型', whitespace: true }],
                                        initialValue: objectInfo.custType ? objectInfo.custType : ""
                                })(
                                    <Select style={{width:'120px'}} placeholder="请输入" >
                                        {
                                            optionData.map((es,sIndex)=>{
                                            return (
                                                <Option key={sIndex} value={es.dicCode}>{es.dicName}</Option>
                                            )
                                            })
                                        }
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        
                    </Row>
                    <Row className="infoForm_row">
                        <Col span={colNumber} >
                            <FormItem  {...formItemLayout} label="入库序列号验证">
                                {
                                    getFieldDecorator('inSeriesVerify', {
                                        rules: [{ required: true, message: '请选择', whitespace: true }],
                                        initialValue: objectInfo.inSeriesVerify ? objectInfo.inSeriesVerify + "" : "1"
                                })(
                                    <RadioGroup name='inSeriesVerify' >
                                        <Radio value="1">是</Radio>
                                        <Radio value="0">否</Radio>
                                    </RadioGroup>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={colNumber} >
                            <FormItem  {...formItemLayout} label="生效期">
                                {
                                    getFieldDecorator('effectiveDate', {
                                        rules: [{ required: false, type: 'object', message: '请选择时间', whitespace: true }],
                                        initialValue: objectInfo.effectiveDate ? moment(objectInfo.effectiveDate, dateFormat): null
                                })(
                                    <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={colNumber} >
                            <FormItem  {...formItemLayout} label="允许超量收货">
                                {
                                    getFieldDecorator('allowExcessReceipt', {
                                    rules: [{ required: false, message: '请选择', whitespace: true }],
                                    initialValue: objectInfo.allowExcessReceipt? objectInfo.allowExcessReceipt : ""
                                })(
                                    <RadioGroup name='allowExcessReceipt' >
                                        <Radio value="1">是</Radio>
                                        <Radio value="0">否</Radio>
                                    </RadioGroup>
                                )}
                            </FormItem>
                        </Col>                        
                    </Row>
                    <Row className="infoForm_row">
                        <Col span={colNumber} >
                            <FormItem  {...formItemLayout} label="出库序列号验证">
                                {
                                    getFieldDecorator('outSeriesVerify', {
                                        rules: [{ required: true, message: '请选择', whitespace: true }],
                                        initialValue: objectInfo.outSeriesVerify ? objectInfo.outSeriesVerify + "" : "1"
                                })(
                                    <RadioGroup name='outSeriesVerify' >
                                        <Radio value="1">是</Radio>
                                        <Radio value="0">否</Radio>
                                    </RadioGroup>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={colNumber} >
                            <FormItem  {...formItemLayout} label="失效期">
                                {
                                    getFieldDecorator('expirationDate', {
                                        rules: [{ required: false, type: 'object', message: '请选择时间', whitespace: true }],
                                        initialValue: objectInfo.expirationDate ? moment(objectInfo.expirationDate, dateFormat): null
                                })(
                                    <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={colNumber} >
                            <FormItem  {...formItemLayout} label="超额收货百分比">
                                {
                                    getFieldDecorator('excessReceiptPercent', {
                                    rules: [{pattern: /^\d+$/, required: false, message: '请输入数字'}],
                                    initialValue: objectInfo.excessReceiptPercent? objectInfo.excessReceiptPercent + "" : ""
                                })(
                                    <Input placeholder="请输入" />
                                )}
                            </FormItem>
                        </Col>                        
                    </Row>                    
                    {/*操作按钮*/}
                    {actionButtons}
                </Form>
            </div>
        );
    }
}
